import { WareHouseFilter, WareHouse } from "../inventory/warehouse"
import { TestConfig } from "../common/testConfig";
import { TestSimulateData } from "../testMgr/testSimulateData"; // 添加的导入
import {
    getWarehouseData, getWarehouseDetail, getInventoryBatchData,
    getPendingInventoryData, getInventoryBatchDetailInfo,
    delInventoryType, editInventoryType, createInventoryType, getInventoryInTypeData,
    reviewInventory, updateOrCreateInventoryBatch,
    getSubCommodityInventorySumData, getSubCommodityInventorySumDataV2, withdrawReviewAndDeleteOrder,
    getInventoryAssemblerData, updateOrCreateInventoryAssembler, getInventoryAssemblerDetailInfo,
    getInventorySheetData, updateOrCreateInventorySheet, getInventorySheetDetailInfo, removeInventorySheet,
    getInventoryInOutRecordData
} from "../../network/api";
import { ApiReturnStruct, getApiData, CommunicationPageData, NetworkParser } from "../../network/communicationConverter";
import { Definition } from "../common/definition";
import { Util } from "../../utils/util";
import { Engine } from "../engine"; // 添加的导入
import { DataPage } from "../../network/communicationConverter"; // 添加的导入
import { CommonOrderStatus, DocType } from '../common/docDefinition';
import { Inventory,InventoryInOutRecord,InventoryInOutType } from '../inventory/inventory.js';
import { FunctionPermissionDefinition } from "../platform/functionPermissionDefinition.js";
import { InventoryType } from "../inventory/inventoryType.js";
import { OrderResult } from "../common/orderResult";
import { SubCommodityInventorySumFilter } from "../commodity/subCommodityInventorySum.js";
import { SubCommodityInventorySumData } from "../commodity/subCommodityInventorySum.js";
import { SubCommodityCollectionPriceMode } from "../commodity/subCommodityCollection.js";
import { CommodityBatchWithTax } from '../sales/sales.js';
import { CsDouble } from "../common/csDouble.js";
import { MessageUtil } from '@/utils/MessageUtil'
import { InventoryAssembler } from "../inventory/inventoryAssembler.js";
import { InventorySheet } from "../inventory/inventorySheet.js";


export class InventoryUiAction {
    ///  获取仓库列表所有信息
    async getWarehouseData(
        {
            orgId = null,  // 组织ID
            pageInfo = null,  // 分页信息 类型DataPage
            showLoadingPage = true,  // 是否显示加载页面
            filter = null,  // 过滤条件 类型WareHouseFilter
        }) {
        if (TestConfig.warehouseTest) {

            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));

            let ret = new ApiReturnStruct();

            let communicationPageData = new CommunicationPageData();
            communicationPageData.pageInfo = pageInfo;
            communicationPageData.dataList = new TestSimulateData().simWareHouseData();

            ret.data = communicationPageData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(WareHouse.fromJson, orgId, pageInfo, getWarehouseData, filter?.toJson(), showLoadingPage);
            return apiData;
        }
    }


    // 获取多仓库列表
    // 显示入库类型页面
    // 该函数不做仓库权限校验
    // 返回 List<WareHouse>

    async getWarehouseList({
        filter = null,  // 过滤条件 类型WareHouseFilter
        showLoadingPage = false,
        maxCount = null,  // 最大数量
    }) {
        maxCount = maxCount ?? Definition.gDefualPageSize;

        filter = filter ?? new WareHouseFilter();

        let wareHouses = [];  // List<WareHouse>



        let apiData = await this.getWarehouseData(
            {
                filter: filter,
                orgId: Engine.profile.org.orgId,
                pageInfo: new DataPage(1, 0, maxCount),
                showLoadingPage: showLoadingPage,
            });


        if (apiData && apiData.data != null) {
            // 显示基本单位页面 houseData 类型 CommunicationPageData < WareHouse >
            let houseData = apiData.data;

            for (let item of houseData.dataList) {
                wareHouses.push(item);
            }

            return wareHouses;
        } else {
            if (apiData?.resErr != null) {
                MessageUtil.showErrorMsg(apiData.resErr);
            }

            return [];
        }
    }


    /// 获取仓库详情
    async getWarehouseDetail(wareHouseId) {

        if (TestConfig.warehouseTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();
            return testSimulateData.simWareHouseData()[0];
        }
        else {
            let res = await getWarehouseDetail(wareHouseId, Engine.profile.org.orgId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, WareHouse.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    // 创建或更新出入库记录
    async updateOrCreateInventoryBatch(inventory, toAudit) {

        const res = await updateOrCreateInventoryBatch(inventory, toAudit)
        // 解析数据，
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
 * 显示仓库详情页面
 * @param {WareHouse} wareHouse - 仓库对象
 * @param {boolean} editMode - 是否编辑模式
 */
    async showWareHouseDetailPage(wareHouse, editMode) {
        let latestWarehouse = wareHouse;

        // 如果仓库有ID，获取最新详情
        if (wareHouse && wareHouse.id) {
            latestWarehouse = await this.getWarehouseDetail(wareHouse.id);
            if (!latestWarehouse) {
                return null;
            }
        }

        // 导航到仓库详情页
        try {
            const result = await uni.navigateTo({
                url: `/pages/inventory/warehouseDetailPage?warehouse=${encodeURIComponent(JSON.stringify(latestWarehouse.toCopyJson()))}&editMode=${editMode}`
            });
        } catch (error) {
            console.error('导航到仓库详情页失败', error);
            return null;
        }
    }

    /**
     * 获取入库单信息
     * @param {string} token - Authentication token
     * @param {string} orgId - Organization ID
     * @param {DataPage} pageInfo - Pagination information
     * @param {Object} [filter] - Filter conditions
     * @returns {Promise<ApiReturnStruct>} - Promise containing API return structure
     */
    async getInventoryData({
        orgId = null,  // 组织ID
        pageInfo = null,  // 分页信息 类型DataPage
        showLoadingPage = true,  // 是否显示加载页面
        filter = {},  // 过滤条件 类型 json
    }) {

        // console.log('getInventoryData', orgId, pageInfo, filter);

        if (TestConfig.inventoryOrderTest) {
            // Simulate delay for testing
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            if (filter && filter['orderType'] == DocType.RKD.code) {
                simData.dataList = testSimulateData.simInventoryInData(filter['a_orderStatus']);
            } else if (filter && filter['orderType'] == DocType.CKD.code) {
                simData.dataList = testSimulateData.simInventoryOutData(filter['a_orderStatus']);
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(Inventory.fromJson, orgId, pageInfo, getInventoryBatchData, filter, showLoadingPage);
            return apiData;
        }
    }

    /**
 * 获取待入库单信息
 * @param {Object} params - Parameters object
 * @param {string} params.token - Authentication token
 * @param {string} params.orgId - Organization ID
 * @param {DataPage} params.pageInfo - Pagination information
 * @param {Object} [params.filter] - Filter conditions
 * @returns {Promise<ApiReturnStruct>} Promise containing API return structure
 */
    async getPendingInventoryData({
        orgId = null,
        pageInfo = null,
        filter = {},
        showLoadingPage = true
    }) {
        if (TestConfig.pendingInventoryInTest) {
            // Simulate delay for testing
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            if (filter && filter['orderType'] == DocType.DRKD.code) {
                simData.dataList = testSimulateData.simPendingInventoryInData();
            } else if (filter && filter['orderType'] == DocType.DCKD.code) {
                simData.dataList = testSimulateData.simPendingInventoryOutData();
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;

            return await getApiData(
                PendingInventory.fromJson,
                orgId,
                pageInfo,
                getPendingInventoryData,
                filter,
                showLoadingPage
            );
        }
    }

    /**
     * 获取出入库单详情
     * @param {string} id - The inventory ID to fetch
     * @returns {Promise<Inventory|null>} 
     */
    async getInventoryDetailInfo(inventoryId) {


        if (TestConfig.inventoryOrderTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            let inventoryData = testSimulateData.simInventoryInData();

            // 查找 匹配的元素
            let inventory = inventoryData.find(item => item.id === inventoryId);
            if (inventory) {
                return inventory;
            }

            return testSimulateData.simInventoryInData()[0];
        }
        else {
            let res = await getInventoryBatchDetailInfo(inventoryId, Engine.profile.org.orgId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, Inventory.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    };

    /// 显示入库单详情 页面
    /// InventoryInOutType inOutType 入库单类型
    async showInventoryDetailPage(inventoryId, inOutType, { editMode = false } = {}) {
        if (inventoryId) {
            uni.navigateTo({
                url: `/pages/inventory/inventoryDetailPage?inventoryId=${inventoryId}&inOutType=${inOutType}&editMode=${editMode}`
            })
        }
        else {
            /*
             let store = Engine.profile?.currentStore;
            if (store && store.isMerchantSuperStore) {
                 StoreUIAction uiAction = StoreUIAction(context);
                var ret = await uiAction.showStoreChoiceDialog(
                    store: Engine.profile!.getValideStore);
                if (ret != null) {
                    store = ret;
                } else {
                    return;
                }
            }
                */
            let store = Engine.profile?.getValideStore;
            let storeParam = "";
            if (store) {
                storeParam = "&storeId=" + store.id + "&storeName=" + store.name;
            }

            console.log("storeParam", storeParam);

            uni.navigateTo({
                url: `/pages/inventory/inventoryDetailPage?inOutType=${inOutType}&editMode=${editMode}` + storeParam
            })
        }
    }

    /**
 * 获取出入库类型
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {InventoryInOutType} options.inOutType - In/out type enum
 * @returns {Promise<ApiReturnStruct>}
 */
    async getInventoryTypeData({
        orgId = null,
        pageInfo = null,
        inOutType = InventoryInOutType.In
    }) {
        if (TestConfig.inventoryInOutTypeTest) {
            // Simulate delay
            await new Promise(resolve => setTimeout(resolve, 1000));

            let ret = new ApiReturnStruct();
            let simData = new CommunicationPageData();

            simData.dataList = inOutType === InventoryInOutType.In
                ? new TestSimulateData().simInventoryInTypeData()
                : new TestSimulateData().simInventoryOutTypeData();

            ret.data = simData;
            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;

            let filter = [];

            if (inOutType == InventoryInOutType.In) {
                filter = { "typeSource": "1" };
            } else if (inOutType == InventoryInOutType.Out) {
                filter = { "typeSource": "0" };
            }

            return await getApiData(
                InventoryType.fromJson,
                orgId,
                pageInfo,
                getInventoryInTypeData,
                filter
            );
        }
    }

    /* 审核出入库单
    
        * @param {string} orgId - Organization ID
        * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
        * @param {InventoryInOutType} inoutType - In/out type enum
     */
    async reviewInventory({
        idList,  // 数组 []
        orgId = null,
    }) {
        let res = await reviewInventory(
            idList,
            orgId ?? Engine.profile.org.orgId,
        )


        // 解析数据，利用 NetworkParser 解析分页数据
        const retData = NetworkParser.parseNetworkResult(res, null);

        return retData;
    }

    /* 删除Inventory 记录
 
  * @param {string} orgId - Organization ID
  * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
  * @param {InventoryInOutType} inoutType - In/out type enum
*/
    async removeInventoryOrder({
        orderId,
        docType, // DocType
    }) {

        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });
        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null &&
            typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除出入库单据失败:" + apiResult.resErr);

            return apiResult;
        }
        return null;
    }

    /* 更新出入库类型
 
    * @param {string} orgId - Organization ID
    * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
    * @param {InventoryInOutType} inoutType - In/out type enum
 */
    async updateOrCreateInventoryType({
        orgId = null,
        inventoryType,
        inoutType
    }) {
        //console.log("updateOrCreateInventoryType", inventoryType, inoutType);
        let res = null;
        if (Util.isEmpty(inventoryType.id)) {
            res = await createInventoryType({
                orgId: orgId ?? Engine.profile.org.orgId,
                inventoryType: inventoryType,
                inoutType: inoutType
            })
        }
        else {
            res = await editInventoryType({
                orgId: orgId ?? Engine.profile.org.orgId,
                inventoryType: inventoryType,
                inoutType: inoutType
            })
        }

        // 解析数据，利用 NetworkParser 解析分页数据
        const retData = NetworkParser.parseNetworkResult(res, null);

        return retData;

    }

    /* 更新出入库类型
 
    * @param {string} orgId - Organization ID
    * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
    * @param {InventoryInOutType} inoutType - In/out type enum
 */
    async delInventoryType({
        orgId = null,
        typeId,
    }) {
        //console.log("delInventoryType:", typeId);
        let res = null;

        res = await delInventoryType({
            orgId: orgId ?? Engine.profile.org.orgId,
            typeId: typeId,
        })


        // 解析数据，利用 NetworkParser 解析分页数据
        const retData = NetworkParser.parseNetworkResult(res, null);

        return retData;

    }

    // 显示入库类型页面
    // inOutType InventoryInOutType
    async showInventoryTypePage(inOutType) {
        // 检查权限
        if (!TestConfig.inventoryInOutTypeTest && !Engine.profile.permissionMgr.hasPermission([
            FunctionPermissionDefinition.P_InventoryTypes_Read,
            FunctionPermissionDefinition.P_InventoryTypes_Edit
        ])) {
            MessageUtil.showWarningMsg("权限不足,无法访问!");
            return null;
        }

        let selectionMode = true;


        uni.navigateTo({
            url: '/pages/inventory/inventoryTypeMgrPage?selectionMode=' + selectionMode + "&inOutType=" + inOutType
        })
    }

    /**
     * 
      WareHouse? excludeWareHouse,
      WareHouseFilter? filter,

      /// 当前选择仓库
      WareHouse? curWareHouse
     */
    async showWarehouseMgrPage({
        selectionMode = false,
        selectLockMode = false,
        excludeWareHouse = null,
        filter = null,
        curWareHouse = null
    } = {}) {
        // Set default filter if not provided
        filter = filter ?? WareHouseFilter.empty();

        // Check permissions
        if (!TestConfig.warehouseTest && !Engine.profile.permissionMgr.hasPermission([
            FunctionPermissionDefinition.P_Warehouse_Read,
            FunctionPermissionDefinition.P_Warehouse_Edit
        ])) {
            MessageUtil.showWarningMsg("权限不足,无法访问!");
            return null;
        }

        let excludeWarehouseParam = excludeWareHouse == null ? "" : `&excludeWareHouse=${excludeWareHouse ? encodeURIComponent(JSON.stringify(excludeWareHouse.toCopyJson())) : ''}`
        let currentWarehousParam = curWareHouse == null ? "" : `&curWarehouse=${encodeURIComponent(JSON.stringify(curWarehouse.toCopyJson()))}`
        let filterParam = filter == null ? "" : `&filter=${encodeURIComponent(JSON.stringify(filter.toCopyJson()))}`

        await uni.navigateTo({
            url: '/pages/inventory/warehouseMgrPage?' +
                `&selectionMode=${selectionMode}` +
                `&selectLockMode=${selectLockMode}` +
                currentWarehousParam + excludeWarehouseParam + filterParam
        });

    }

    /**
 * Get subcommodity batch by scanning QR code
 * @param {Object} options
 * @param {WareHouse} [options.warehouse] - Warehouse object
 * @param {string} options.storeId - Store ID
 * @param {SubCommodityCollectionPriceMode} options.priceMode - Price mode
 * @param {boolean} [options.taxSwitch] - Tax switch (null means use org settings)
 * @returns {Promise<CommodityBatchWithTax|null>}
 */
    async getSubcommoditBatchScanQrCode({
        warehouse = null,  // WareHouse
        storeId = null,
        priceMode,  // 价格模式 SubCommodityCollectionPriceMode
        /// 含税设定，
        /// 如果没有设定含税参数 即 taxSwitch == null, 会根据商户配置判断是否含税
        /// 如果设定了 taxSwitch 则会，以taxSwitch 值为准
        taxSwitch = null
    }) {
        var sumData = await this.getSubcommoditySumDataByScanQrCode({ storeId: storeId });
        if (sumData != null) {
            let price = sumData.subCommodity.retailPrice;
            switch (priceMode) {
                case SubCommodityCollectionPriceMode.purchasePrice:
                    price = sumData.subCommodity.purchasePrice;
                    break;
                case SubCommodityCollectionPriceMode.retailPrice:
                    price = sumData.subCommodity.retailPrice;
                    break;
                case SubCommodityCollectionPriceMode.wholesalePrice:
                    price = sumData.subCommodity.wholesalePrice;
                    break;
                default:
                    break;
            }

            let batchIn = new CommodityBatchWithTax({
                commodity: sumData.subCommodity,
                count: new CsDouble(1),
                availableCount: sumData.availableCount,
                inventoryCount: sumData.totalInventoryCount,
                batchPrice: price,
                singlePrice: price
            });

            // 设置了含税
            if ((priceMode == SubCommodityCollectionPriceMode.retailPrice ||
                priceMode == SubCommodityCollectionPriceMode.wholesalePrice)) {
                // 设置了含税
                if ((taxSwitch != null && taxSwitch) ||
                    (taxSwitch == null &&
                        Engine.getOrgSettings().enableSalesWithTaxDetail)) {
                    // 销售含税
                    // batchIn = batchIn;
                } else {
                    batchIn = CommodityBatchWithTax.fromCommodityBatchWithTaxSimpleMode(
                        batchIn);
                }
            } else if ((priceMode == SubCommodityCollectionPriceMode.purchasePrice)) {
                if ((taxSwitch != null && taxSwitch) ||
                    (taxSwitch == null &&
                        Engine.getOrgSettings().enablePurchaseWithTaxDetail)) {
                    // 采购含税
                    //batchIn = batchIn;
                } else {
                    batchIn = CommodityBatchWithTax.fromCommodityBatchWithTaxSimpleMode(
                        batchIn);
                }
            }

            return batchIn;
        }
        return null;
    }

    /**
     * 获取商品库存信息
     * Get subcommodity inventory sum data
     * @param {string} token - Authentication token
     * @param {string} orgId - Organization ID
     * @param {DataPage} pageInfo - Pagination info
     * @param {Object} [filter] - Filter conditions
     * @param {boolean} [justIncludeRelatedCommodity=false] - 只包含建立了商品与仓库关系的商品 Only include related commodities
     * @returns {Promise<ApiReturnStruct>}
     */
    async getSubCommodityInventorySumData(
        {
            orgId = null,
            pageInfo,
            filter = null,
            /// 只包含建立了商品与仓库关系的商品
            justIncludeRelatedCommodity = false
        }
    ) {
        if (TestConfig.subCommodityInventorySumTest) {
            // Simulate delay
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            simData.dataList = new TestSimulateData().simSubCommodityInventorySumData();

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {

            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空

            let functionToUse = justIncludeRelatedCommodity
                ? getSubCommodityInventorySumData
                : getSubCommodityInventorySumDataV2;

            let apiData = await getApiData(
                SubCommodityInventorySumData.fromJson,
                orgId,
                pageInfo,
                functionToUse,
                filter
            );

            return apiData;
        }
    }

    /**
     * 获取组装拆卸单信息
     * @param {Object} options
     * @param {string} options.token - Authentication token
     * @param {string} options.orgId - Organization ID
     * @param {DataPage} options.pageInfo - Pagination information
     * @param {Object} [options.filter] - Filter conditions
     * @param {boolean} [options.showLoadingPage=true] - Whether to show loading page
     * @returns {Promise<ApiReturnStruct>} - Promise containing API return structure
     */
    async getInventoryAssemblerData({
        orgId = null,  // 组织ID
        pageInfo = null,  // 分页信息 类型DataPage
        showLoadingPage = true,  // 是否显示加载页面
        filter = null,  // 过滤条件 类型 json
    }) {
        console.log('getInventoryAssemblerData', orgId, pageInfo, filter);

        if (TestConfig.inventoryAssemblerTest) {
            // Simulate delay for testing
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            simData.dataList = testSimulateData.simInventoryAssemblerData(
                filter && filter['a_orderStatus'] !== undefined ? filter['a_orderStatus'] : null
            );

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(InventoryAssembler.fromJson, orgId, pageInfo, getInventoryAssemblerData, filter, showLoadingPage);
            return apiData;
        }
    }

    // 创建或更新组装拆卸单记录
    async updateOrCreateInventoryAssembler(inventoryAssembler, toAudit) {

        const res = await updateOrCreateInventoryAssembler(inventoryAssembler, toAudit)
        // 解析数据，
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
 * 获取出入库单详情
 * @param {string} id - The inventory ID to fetch
 * @returns {Promise<InventoryAssembler|null>} 
 */
    async getInventoryAssemblerDetailInfo(orderId) {


        if (TestConfig.inventoryAssemblerTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            let inventoryData = testSimulateData.simInventoryAssemblerData();

            // 查找 匹配的元素
            let inventory = inventoryData.find(item => item.id === orderId);
            if (inventory) {
                return inventory;
            }

            return testSimulateData.simInventoryAssemblerData()[0];
        }
        else {
            let res = await getInventoryAssemblerDetailInfo(orderId, Engine.profile.org.orgId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, InventoryAssembler.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    };

    /* 删除InventoryAssembler 记录
    * @param {string} orgId - Organization ID
    * @param {InventoryType} inventoryType - Inventory type data 类型：InventoryType
    * @param {InventoryInOutType} inoutType - In/out type enum
    */
    async removeInventoryAssemberOrder({
        orderId,
        docType, // DocType
    }) {

        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });
        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null &&
            typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除组装拆卸单据失败:" + apiResult.resErr);

            return apiResult;
        }
        return null;
    }

    ////////////////////////////////////////  盘点单开始
    /**
     * 获取盘点单列表
     * @param {Object} options
     * @param {string} options.orgId - Organization ID
     * @param {DataPage} options.pageInfo - Pagination information
     * @param {Object} [options.filter] - Filter conditions
     * @param {boolean} [options.showLoadingPage=true] - Whether to show loading page
     * @returns {Promise<ApiReturnStruct>} - Promise containing API return structure
     */
    async getInventorySheetData({
        orgId = null,  // 组织ID
        pageInfo = null,  // 分页信息 类型DataPage
        showLoadingPage = true,  // 是否显示加载页面
        filter = null,  // 过滤条件 类型 json
    }) {
        console.log('getInventorySheetData', orgId, pageInfo, filter);

        if (TestConfig.inventorySheetTest) {
            // Simulate delay for testing
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            simData.dataList = testSimulateData.simInventorySheetData(
                filter && filter['a_orderStatus'] !== undefined ? filter['a_orderStatus'] : null
            );

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId; // 获取当前组织ID 不在默认参数设置，避免TestConfig.warehouseTest 测试时，orgId为空
            let apiData = await getApiData(InventorySheet.fromJson, orgId, pageInfo, getInventorySheetData, filter, showLoadingPage);
            return apiData;
        }
    }

    // 创建或更新盘点单记录
    async updateOrCreateInventorySheet(inventorySheet, toAudit) {
        const res = await updateOrCreateInventorySheet(inventorySheet, toAudit)
        // 解析数据，
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 获取盘点单详情
     * @param {string} orderId - The inventory sheet ID to fetch
     * @returns {Promise<InventorySheet|null>} 
     */
    async getInventorySheetDetailInfo(orderId) {
        if (TestConfig.inventorySheetTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            let inventoryData = testSimulateData.simInventorySheetData();

            // 查找 匹配的元素
            let inventory = inventoryData.find(item => item.id === orderId);
            if (inventory) {
                return inventory;
            }

            return testSimulateData.simInventorySheetData()[0];
        }
        else {
            let res = await getInventorySheetDetailInfo(orderId, Engine.profile.org.orgId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, InventorySheet.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 删除盘点单记录
     * @param {Object} options
     * @param {string} options.orderId - Order ID
     * @param {DocType} options.docType - Document type
     * @returns {Promise<any|null>}
     */
    async removeInventorySheetOrder({
        orderId,
        docType, // DocType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });
        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null &&
            typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除盘点单据失败:" + apiResult.resErr);

            return apiResult;
        }
        return null;
    }

    ////////////////////////////////////////  盘点单结束

    ////////////////////////////////////////  出入库明细开始
    /**
 * 获取出入库明细记录数据
 * Get inventory in/out record data
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination info
 * @param {Object} [options.filter] - Filter conditions
 * @param {boolean} [options.showLoadingPage=true] - Whether to show loading page
 * @returns {Promise<ApiReturnStruct>}
 */
    async getInventoryInOutRecordData({
        orgId = null,
        pageInfo = null,
        filter = null,
        showLoadingPage = true
    }) {
        if (TestConfig.inventoryInOutRecordTest) {
            // Simulate delay for testing
            await new Promise(resolve => setTimeout(resolve, 1000));

            let simData = new CommunicationPageData();
            const testSimulateData = new TestSimulateData();

            if (filter != null && filter['state'] === 0) {
                simData.dataList = testSimulateData.simAllInventoryInOutRecordData();
            } else if (filter != null && filter['state'] === 1) {
                simData.dataList = testSimulateData.simInventoryInRecordData();
            } else if (filter != null && filter['state'] === 2) {
                simData.dataList = testSimulateData.simInventoryOutRecordData();
            } else {
                simData.dataList = testSimulateData.simAllInventoryInOutRecordData();
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;

            return ret;
        } else {
            orgId = orgId ?? Engine.profile.org.orgId;
            return await getApiData(
                InventoryInOutRecord.fromJson,
                orgId,
                pageInfo,
                getInventoryInOutRecordData,
                filter,
                showLoadingPage
            );
        }
    }

    ////////////////////////////////////////  出入库明细结束

    /**
 * 二维码扫码选择商品
 * QR code scanning to select commodity
 * @param {Object} options
 * @param {WareHouse} [options.warehouse] - Warehouse object
 * @param {string} options.storeId - Store ID
 * @returns {Promise<SubCommodityInventorySumData|null>}
 */
    async getSubcommoditySumDataByScanQrCode({
        warehouse = null,  // WareHouse
        storeId = null
    }) {
        // Show QR scan page
        const qrValue = await Util.scanQrAndBarCodeAsync();

        if (qrValue != null && typeof qrValue === 'string') {
            // MessageUtil.showInfo("QrCode:" + qrValue);

            const filter = new SubCommodityInventorySumFilter({ storeId: storeId });
            filter.wareHouse = warehouse;
            filter.fullMatchQRCode = qrValue;
            //filter.qrCode = qrValue;

            // 重新加载商品列表
            // Reload commodity list
            // monitor network fetch
            try {
                const apiData = await this.getSubCommodityInventorySumData(
                    {
                        pageInfo: new DataPage(1, 0, Definition.gDefualPageSize),
                        filter: filter.toJson()
                    }
                );



                if (apiData.data != null) {
                    const sumData = apiData.data; // CommunicationPageData<SubCommodityInventorySumData>

                    if (sumData.dataList.length === 0) {
                        // 无对应商品
                        // No matching commodity
                        MessageUtil.showWarningMsg("无匹配商品:" + qrValue);
                        return null;
                    } else if (sumData.dataList.length === 1) {
                        // 唯一商品
                        // Only one commodity
                        return sumData.dataList[0];
                    } else {
                        // todo 多个匹配商品 多个匹配商品，进行选择
                        // 暂时不构建该页面，直接返回第一个商品
                        // Multiple matching commodities
                        return sumData.dataList[0];
                        /*
                        const ret = await uni.navigateTo({
                            url: '/pages/inventory/subCommodityWithInventoryDataSelectionPageForQrCode',
                            success: (res) => {
                                res.eventChannel.emit('initData', {
                                    sumData: sumData,
                                    initFilter: filter.toJson()
                                });
                            }
                        });

                        if (ret && ret instanceof SubCommodityInventorySumData) {
                            return ret;
                        }

                        */

                    }
                } else {
                    if (apiData.resErr != null && typeof apiData.resErr === 'string') {
                        MessageUtil.showErrorMsg(apiData.resErr);
                    }
                }
            } catch (error) {

                console.error('QR code scan failed:', error);
            }
        }

        return null;
    }

}